// API基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000'

// HTTP请求工具类
class HttpClient {
  constructor(baseURL = API_BASE_URL) {
    this.baseURL = baseURL
    this.token = localStorage.getItem('token')
  }

  // 设置token
  setToken(token) {
    this.token = token
    if (token) {
      localStorage.setItem('token', token)
    } else {
      localStorage.removeItem('token')
    }
  }

  // 获取用户ID
  getUserId() {
    try {
      // 从localStorage获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      return userInfo.id || null
    } catch (e) {
      console.warn('获取用户信息失败:', e)
      return null
    }
  }

  // 获取请求头
  getHeaders() {
    const headers = {
      'Content-Type': 'application/json'
    }
    
    // 每次都从localStorage获取最新的token
    const currentToken = localStorage.getItem('token')
    if (currentToken) {
      headers.Authorization = `Bearer ${currentToken}`
    }
    
    return headers
  }

  // 处理响应
  async handleResponse(response) {
    if (!response.ok) {
      let errorMessage = `HTTP ${response.status}`
      let errorData = null
      
      try {
        const contentType = response.headers.get('content-type')
        if (contentType && contentType.includes('application/json')) {
          errorData = await response.json()
          errorMessage = errorData.error || errorData.message || errorData.title || errorMessage
        } else {
          const textError = await response.text()
          errorMessage = textError || errorMessage
        }
      } catch (e) {
        // 如果解析错误响应失败，使用默认错误信息
        console.warn('解析错误响应失败:', e)
      }
      
      console.error('HTTP请求失败:', { status: response.status, url: response.url, errorData, errorMessage })
      
      const error = new Error(errorMessage)
      error.status = response.status
      error.response = { data: errorData }
      throw error
    }
    
    const contentType = response.headers.get('content-type')
    if (contentType && contentType.includes('application/json')) {
      return await response.json()
    }
    
    return await response.text()
  }

  // GET请求
  async get(url) {
    const response = await fetch(`${this.baseURL}${url}`, {
      method: 'GET',
      headers: this.getHeaders()
    })
    return this.handleResponse(response)
  }

  // POST请求
  async post(url, data) {
    const response = await fetch(`${this.baseURL}${url}`, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify(data)
    })
    return this.handleResponse(response)
  }

  // PUT请求
  async put(url, data) {
    const response = await fetch(`${this.baseURL}${url}`, {
      method: 'PUT',
      headers: this.getHeaders(),
      body: JSON.stringify(data)
    })
    return this.handleResponse(response)
  }

  // DELETE请求
  async delete(url) {
    const response = await fetch(`${this.baseURL}${url}`, {
      method: 'DELETE',
      headers: this.getHeaders()
    })
    return this.handleResponse(response)
  }

    // 文件上传请求
  async upload(url, formData) {
    const headers = {}
    if (this.token) {
      headers.Authorization = `Bearer ${this.token}`
    }
    
    // 获取用户ID
    const userId = this.getUserId()
    
    if (!userId) {
      console.error('用户未登录或用户ID不存在')
      throw new Error('请先登录后再上传文档')
    }
    
    headers['X-User-Id'] = userId
    console.log('文件上传请求头:', { userId, hasToken: !!this.token })

    const response = await fetch(`${this.baseURL}${url}`, {
      method: 'POST',
      headers,
      body: formData
    })
    return this.handleResponse(response)
  }
}

export default new HttpClient()
